import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:frontend/pages/homePage.dart';
import 'package:frontend/pages/orderPage.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:frontend/states/cartState.dart';
import 'package:provider/provider.dart';
import 'package:frontend/pages/personalChattingPage.dart';

import '../models/global.dart';

class ItemPage extends StatefulWidget {
  const ItemPage({super.key, required this.itemId, this.canBuy = true});

  @override
  State<StatefulWidget> createState() => ItemPageState();
  final int itemId;
  final bool canBuy;
}

class ItemPageState extends State<ItemPage> {
  late TextEditingController commentController;

  @override
  void initState() {
    super.initState();
    commentController = TextEditingController();
  }

  _buildDivider() {
    return Divider(
      color: Theme.of(context).textTheme.caption!.color,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("物品详情"),
      ),
      body: FutureBuilder(
          future: queryItemInfo(widget.itemId),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                return const Icon(Icons.error);
              } else {
                return Container(
                  padding: const EdgeInsets.all(24),
                  child: ListView(
                    children: [
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 500.0,
                            width: 350.0,
                            child: Image.memory(snapshot.data!.img),
                          ),
                          Column(
                            children: [
                              Text(
                                snapshot.data!.name,
                                style: TextStyle(
                                  fontSize: 42.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Text(
                                '￥ ${snapshot.data!.price}',
                                style: TextStyle(
                                    fontSize: 28.0,
                                    fontWeight: FontWeight.w200,
                                    color: Colors.grey),
                              ),
                              Text(
                                snapshot.data!.description,
                                style: TextStyle(
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.normal,
                                ),
                              )
                            ],
                          ),
                        ],
                      ),
                      _buildDivider(),
                      Row(
                        children: [
                          if (widget.canBuy)
                            ElevatedButton(
                                onPressed: () {
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: ((context) =>
                                              personalChattingPage(
                                                  snapshot.data!.seller_id))));
                                },
                                child: const Text("联系卖家")),
                          if (widget.canBuy)
                            ElevatedButton(
                                onPressed: () {
                                  if (!Global.profile.isLogin) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text('请先登录'),
                                      ),
                                    );
                                  } else {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => OrderPage(
                                                itemId: widget.itemId)));
                                  }
                                },
                                child: const Text("立即下单")),
                          if (widget.canBuy)
                            ElevatedButton(
                                onPressed: () {
                                  if (!Global.profile.isLogin) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text('请先登录'),
                                      ),
                                    );
                                  } else {
                                    addToCart(Global.profile.user!.id,
                                        snapshot.data!.id);
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text('已加入购物车'),
                                      ),
                                    );
                                  }
                                },
                                child: const Text("加入购物车")),
                          Text(snapshot.data!.ownerName)
                        ],
                      ),
                      _buildDivider(),
                      Container(
                        constraints: BoxConstraints.tightFor(height: 180.0),
                        child: Scrollbar(
                          child: ListView.builder(
                              itemCount: snapshot.data!.comments.length,
                              itemBuilder: (context, index) {
                                //print(snapshot.data!.comments[0].content);
                                return Comment2(
                                    userAvatar:
                                        snapshot.data!.comments[index].userImg,
                                    userName:
                                        snapshot.data!.comments[index].userName,
                                    comment:
                                        snapshot.data!.comments[index].content);
                              }),
                        ),
                      ),
                      Card(
                          elevation: 0,
                          color: Theme.of(context).colorScheme.surfaceVariant,
                          child: Column(
                            children: [
                              TextField(
                                controller: commentController,
                                decoration: const InputDecoration(
                                  border: OutlineInputBorder(),
                                  labelText: "输入评论",
                                ),
                              ),
                              ElevatedButton(
                                  onPressed: () {
                                    if (!Global.profile.isLogin) {
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(
                                        const SnackBar(
                                          content: Text('请先登录'),
                                        ),
                                      );
                                    } else {
                                      submitComment(
                                              snapshot.data!.id,
                                              Global.profile.user!.id,
                                              commentController.text)
                                          .onError((error, stackTrace) =>
                                              ScaffoldMessenger.of(context)
                                                  .showSnackBar(
                                                const SnackBar(
                                                  content: Text('发送失败'),
                                                ),
                                              ))
                                          .then((_) {
                                        setState(() {});
                                        return ScaffoldMessenger.of(context)
                                            .showSnackBar(
                                          const SnackBar(
                                            content: Text('发送成功'),
                                          ),
                                        );
                                      });
                                    }
                                  },
                                  child: const Text("发布评论"))
                            ],
                          )),
                      /*ListView.builder(
                          itemCount: snapshot.data!.comments.length,
                          itemBuilder: (context, index) {
                            return Comment(
                                userAvatar: Image.memory(
                                    snapshot.data!.comments[index].userImg),
                                userName: snapshot.data!.comments[index].userName,
                                comment: snapshot.data!.comments[index].content);
                          })*/
                    ],
                  ),
                );
              }
            } else {
              // 请求未结束，显示loading
              return const CircularProgressIndicator();
            }
          }),
    );
  }
}

class Comment extends StatelessWidget {
  const Comment(
      {super.key,
      required this.userAvatar,
      required this.userName,
      required this.comment});

  final Uint8List userAvatar;
  final String userName;
  final String comment;

  @override
  Widget build(BuildContext context) {
    return Card(
        elevation: 0,
        color: Theme.of(context).colorScheme.surfaceVariant,
        child: Column(
          children: [
            Container(
              child: Row(
                children: [
                  CircleAvatar(
                    child: Image.memory(userAvatar),
                  ),
                  Text(userName)
                ],
              ),
            ),
            Text(comment)
          ],
        ));
  }
}

class Comment2 extends StatelessWidget {
  const Comment2(
      {super.key,
      required this.userAvatar,
      required this.userName,
      required this.comment});

  final Uint8List userAvatar;
  final String userName;
  final String comment;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      contentPadding: EdgeInsets.all(6.0),
      leading: CircleAvatar(
        child: Image.memory(userAvatar),
      ),
      title: RichText(
        text: TextSpan(
            text: userName,
            style: TextStyle(
                color: Colors.blue, fontWeight: FontWeight.w600, fontSize: 16),
            children: [
              TextSpan(
                  text: "  发表了评论",
                  style: TextStyle(color: Colors.grey, fontSize: 14)),
            ]),
      ),
      subtitle: Text(
        comment,
        style: TextStyle(color: Colors.black54),
      ),
    );
  }
}
